#!/usr/bin/env python
#coding=utf-8
import sys
sys.path.append('/home/jay/xiaojaylib/gae')
import os
os.environ['DJANGO_SETTINGS_MODULE'] = 'gae_manager.settings'
from gae_manager.host.models import Project

COL_NONE = "\033[0m"
COL_RED  = "\033[0;31;48m"

import subprocess
command = 'appcfg.py --passin --email=%s --no_cookies update %s'

def prepare_app_config(project, app_id):
    '''重写app_id 到 app.yaml和setting.py'''
    fp = os.path.join(project.path, 'app.yaml')

    content = open(fp).readlines()
    content[0] = 'application: %s\n'%app_id
    open(fp, 'w').writelines(content)
    
    fp = os.path.join(project.path, 'settings.py')
    content = open(fp).readlines()
    content[0] = 'application= "%s"\n'%app_id
    open(fp, 'w').writelines(content)

project_name = sys.argv[1]
project = Project.objects.get(name = project_name)
path = project.path

for app in project.app_set.all():

    prepare_app_config(project, app.app_id)

    account = app.account  
    complete_command = command%(account.email, path)

    print '\n\n%s %s %s\n'%(COL_RED, complete_command, COL_NONE)

    p = subprocess.Popen(complete_command, shell=True, stdin=subprocess.PIPE)
    p.communicate(account.password)



